import { defineStore } from "pinia";
import { computed, ref } from "vue";
import request from "@/utils/request";
import type { ApiRes, CartItem } from "@/types/data";
import useStore from "..";

const useCartStore = defineStore(
  "cart",
  () => {
    const list = ref([] as CartItem[]);

    // 添加购物车
    const addCart = async (data: CartItem) => {
      if (isLogin.value) {
        const res = await request.post("/member/cart", {
          skuId: data.skuId,
          count: data.count,
        });
        getCartList();
      } else {
        // console.log(data);
        // 判断skuId是否已经存在于list数组中
        // 1.存在是数量增加
        // 2.不存是数组新增成员

        const index = list.value.findIndex((sku) => {
          return sku.skuId === data.skuId;
        });

        if (index != -1) {
          list.value[index].count += data.count;
        } else {
          list.value.unshift(data);
        }
      }
    };

    // 获取购物车列表
    const getCartList = async () => {
      if (isLogin.value) {
        const res = await request.get<ApiRes<CartItem[]>>("/member/cart");
        list.value = res.data.result;
      } else {
        console.log("未登录时获取购物车列表");
      }
    };

    // 删除购物车数据
    const deleteCart = async (ids: string[]) => {
      if (isLogin.value) {
        await request.delete("/member/cart", { data: { ids } });
        getCartList();
      } else {
        // ids是数组：[1,2,3]   1

        ids.forEach((id) => {
          const index = list.value.findIndex((item) => {
            return item.skuId === id;
          });
          list.value.splice(index, 1);
        });
      }
    };

    // 修改购物车商品状态与数量
    const updateCart = async (
      skuId: string,
      { selected, count }: { selected?: boolean; count?: number }
    ) => {
      if (isLogin.value) {
        await request.put(`/member/cart/${skuId}`, { selected, count });
        getCartList();
      } else {
        const sku = list.value.find((item) => {
          return item.skuId === skuId;
        });

        if (count !== undefined) sku!.count = count;
        if (selected !== undefined) sku!.selected = selected;
      }
    };

    // 修改所有购物车商品状态
    const updateAllCart = async ({
      selected,
      skuIds,
    }: {
      selected: boolean;
      skuIds: string[];
    }) => {
      if (isLogin.value) {
        await request.put(`/member/cart/selected`, { selected, skuIds });
        getCartList();
      } else {
        list.value.forEach((item) => {
          item.selected = selected;
        });
      }
    };

    // 清空购物车商品数据
    const clearCartList = () => {
      list.value = [] as CartItem[];
    };

    // 登录后购物车的合并
    const mergeLocalCart = async () => {
      const data = list.value.map(({ skuId, selected, count }) => {
        return {
          skuId,
          selected,
          count,
        };
      });

      await request.post("/member/cart/merge", data);

      getCartList();
    };

    // 计算属性判断用户是否登录
    const isLogin = computed(() => {
      const { user } = useStore();
      return !!user.userInfo.token;
    });

    // 计算属性获取有效商品
    const effectiveList = computed(() => {
      return list.value.filter((item) => item.isEffective);
    });

    // 计算属性获取商品总数量
    const effectiveListCount = computed(() => {
      return effectiveList.value.reduce((acc, item) => (acc += item.count), 0);
    });

    // 计算属性获取商品总价格
    const effectiveListPrice = computed(() => {
      return effectiveList.value.reduce(
        (acc, item) => (acc += item.count * parseFloat(item.price)),
        0
      );
    });

    // 计算属性获取所有的有效商品的选中状态
    const isEffectiveSelected = computed(() => {
      return (
        effectiveList.value.length > 0 &&
        effectiveList.value.every((item) => item.selected)
      );
    });

    const selectedList = computed(() => {
      return effectiveList.value.filter((item) => item.selected);
    });

    const slectedListCount = computed(() => {
      return selectedList.value.reduce((acc, item) => (acc += item.count), 0);
    });

    const slectedListPrice = computed(() => {
      return selectedList.value.reduce(
        (acc, item) => (acc += item.count * parseFloat(item.nowPrice)),
        0
      );
    });

    return {
      list,
      addCart,
      getCartList,
      deleteCart,
      updateCart,
      updateAllCart,
      clearCartList,
      mergeLocalCart,
      effectiveList,
      effectiveListCount,
      effectiveListPrice,
      isEffectiveSelected,
      slectedListCount,
      slectedListPrice,
    };
  },
  {
    persist: true,
  }
);

export default useCartStore;
